<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          v-hasPermi="['produce:numAdjust:query']"
        >
          查询
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleAdjust"
          :disabled="single"
          v-hasPermi="['produce:numAdjust:Adjust']"
        >
          调整
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['produce:numAdjust:export']"
        >
          导出
        </el-button>
      </el-col>
      <hd-tag-group :show="['jinxing', 'dengdai', 'zanting', 'wancheng']" />
      <el-col :span="2.2" style="position: absolute; right: 35px; top: 0">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
    </el-row>

    <el-table
      :row-class-name="rowClass"
      highlight-current-row
      border
      stripe
      v-loading="loading"
      @row-click="clickMoe"
      :data="moeDetList"
      show-summary
      :summary-method="getSummaries"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column
        label="#"
        width="40"
        align="center"
        type="index"
        fixed="left"
      />
      <el-table-column
        label="制造单号"
        :show-overflow-tooltip="true"
        fixed="left"
        width="120"
        align="center"
        prop="moeZzdh"
      />
      <el-table-column
        label="机台"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeJtbh"
      />
      <el-table-column
        label="营销单客户编号"
        fixed="left"
        :show-overflow-tooltip="true"
        width="120"
        align="center"
        prop="somCustwldm"
      />
      <el-table-column
        label="制造单客户编号"
        fixed="left"
        :show-overflow-tooltip="true"
        width="120"
        align="center"
        prop="itmCustwldm"
      />
      <el-table-column
        label="生产数量"
        fixed="left"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeScsl"
      />
      <el-table-column
        label="良品数量"
        fixed="left"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeLpsl"
      />
      <el-table-column
        label="入库数量"
        fixed="left"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeRksl"
      />
      <el-table-column
        label="调整数量"
        fixed="left"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeTzsl"
      />
      <el-table-column
        label="物料代码"
        :show-overflow-tooltip="true"
        width="135"
        align="center"
        prop="moeWldm"
      />
      <el-table-column
        label="品名规格"
        :show-overflow-tooltip="true"
        width="400"
        prop="itmPmgg"
      />
      <el-table-column
        label="销售单号"
        :show-overflow-tooltip="true"
        width="120"
        align="center"
        prop="moeSodh"
      />
      <el-table-column
        label="模具编号"
        :show-overflow-tooltip="true"
        width="120"
        align="center"
        prop="moeMjbh"
      />
      <el-table-column
        label="组别"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeBbdm"
      />
      <el-table-column
        label="生产日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="moeScrq"
        width="150"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.moeScrq, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="序号"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeScxh"
      />
      <el-table-column
        label="调机不良"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeTjbl"
      />
      <el-table-column
        label="工程不良"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeWxbl"
      />
      <el-table-column
        label="生产不良"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeYxbl"
      />
      <el-table-column
        label="操作人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="moeCzry"
      />
    </el-table>
    <!-- 查询对话框   -->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="650px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="24">
          <el-form-item label="完工日期" prop="dateRange">
            <el-date-picker
              clearable
              size="small"
              v-model="dateRange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              style="width: 520px"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="制造单号" prop="moeZzdh">
            <el-input
              v-model="queryParams.moeZzdh"
              placeholder="请输入制造单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售单号" prop="moeSodh">
            <el-input
              v-model="queryParams.moeSodh"
              placeholder="请输入销售单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="moeWldm">
            <el-input
              v-model="queryParams.moeWldm"
              placeholder="请输入物料代码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="机台编号" prop="moeJtbh">
            <el-input
              v-model="queryParams.moeJtbh"
              placeholder="请输入机台编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模具编号" prop="moeMjbh">
            <el-input
              v-model="queryParams.moeMjbh"
              placeholder="请输入模具编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="综合查询" prop="moePmgg">
            <el-input
              v-model="queryParams.moePmgg"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="moeZtbz">
            <el-radio-group
              style="margin-left: 90px"
              v-model="queryParams.moeZtbz"
            >
              <el-radio
                v-for="dict in orderStatusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >
                {{ dict.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>

    <!-- 调整 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="680px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-col :span="12">
          <el-form-item label="制造单号" prop="moeZzdh">
            <el-input v-model="form.moeZzdh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售单号" prop="moeSodh">
            <el-input v-model="form.moeSodh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="moeWldm">
            <el-input v-model="form.moeWldm" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品名规格" prop="itmPmgg">
            <el-input v-model="form.itmPmgg" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划数量" prop="moeScsl">
            <el-input v-model="form.moeScsl" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模具编号" prop="moeMjbh">
            <el-input v-model="form.moeMjbh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="良品数量" prop="moeLpsl">
            <el-input v-model="form.moeLpsl" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产不良" prop="moeYxbl">
            <el-input v-model="form.moeYxbl" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="调整类别" prop="tzlTzlb">
            <el-select
              v-model="form.tzlTzlb"
              filterable
              placeholder="请选择调整类别"
              clearable
            >
              <el-option
                v-for="item in adjustOptions"
                :key="item.dictValue"
                :label="'[' + item.dictValue + ']' + item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可调整数量">
            {{ form.moeScsl - form.moeLpsl }}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="调整数量" prop="tzlTzsl">
            <el-input-number
              v-model="form.tzlTzsl"
              placeholder="请输入调整数量"
              :max="form.moeScsl - form.moeLpsl"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="调整原因" prop="tzlTzyy">
            <el-input
              v-model="form.tzlTzyy"
              type="textarea"
              placeholder="请输入调整原因"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, adjust } from "@/api/production/numAdjust";
import { getMoeDet } from "@/api/produce/moeDet";

export default {
  name: "NumAdjust",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 非单个禁用
      single: true,
      tableH: document.body.clientHeight - 230,
      // 显示搜索条件
      showSearch: true,
      openSearch: false,
      // 总条数
      total: 0,
      // 工单表格数据
      moeDetList: [],
      //选择的id
      ids: null,
      // 日期范围
      dateRange: [
        this.$moment().startOf("month").format(),
        this.$moment().endOf("month").format(),
      ],
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      // 表单重置
      reset() {
        this.form = {
          moeId: null,
          moeZzdh: null,
          moeSodh: null,
          moeWldm: null,
          itmPmgg: null,
          moeScsl: null,
          moeMjbh: null,
          moeLpsl: null,
          moeYxbl: null,
          tzlTzlb: null,
          tzlTzsl: null,
          tzlTzyy: null,
        };
        this.resetForm("form");
      },
      //表单效验
      rules: {
        tzlTzlb: [
          { required: true, message: "调整类别不能为空", trigger: "blur" },
        ],
        tzlTzsl: [
          { required: true, message: "调整数量不能为空", trigger: "blur" },
        ],
        // tzlTzyy: [{ required: true, message: '调整原因不能为空', trigger: 'blur' }],
      },
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: document.body.clientHeight > 900 ? 25 : 18,
        moeZzdh: null,
        moeSodh: null,
        moeWldm: null,
        moeJtbh: null,
        moeMjbh: null,
        moePmgg: null,
        moeZtbz: 1,
      },
      //订单状态
      orderStatusOptions: [
        { dictValue: 0, dictLabel: "全部", listClass: "default" },
        { dictValue: 1, dictLabel: "待调整订单", listClass: "default" },
        { dictValue: 2, dictLabel: "待生产订单", listClass: "default" },
        { dictValue: 4, dictLabel: "未结案订单", listClass: "default" },
        { dictValue: 3, dictLabel: "已完成订单", listClass: "default" },
      ],
      //调整类别字典
      adjustOptions: [],
    };
  },
  created() {
    //调整类别
    this.getDicts("production_numAdjust").then((response) => {
      this.adjustOptions = response.data;
    });

    this.getList();
  },
  methods: {
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (this.dateRange !== null) {
        this.queryParams.params["beginDate"] = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParams.params["endDate"] = this.moment(
          this.dateRange[1]
        ).format("YYYY-MM-DD HH:mm:ss");
      }
      list(this.queryParams).then((response) => {
        this.moeDetList = [];
        this.moeDetList = this.moeDetList.concat(response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    //load
    load() {
      if (
        this.queryParams.pageNum <
        Math.ceil(this.total / this.queryParams.pageSize)
      ) {
        this.queryParams.pageNum++;
        list(this.queryParams).then((response) => {
          this.moeDetList = this.moeDetList.concat(response.rows);
          this.total = response.total;
          this.loading = false;
        });
      }
      return 0;
    },
    clickMoe(row) {
      this.single = row.moeId == null || row.moeId == "" ? true : false;
      this.ids = row.moeId;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.moeDetList = [];
      this.getList();
      this.openSearch = false;
    },
    handleSearch() {
      this.title = "良品数查询";
      this.openSearch = true;
    },
    handleAdjust() {
      this.reset();
      getMoeDet(this.ids).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "良品数调整";
      });
    },
    //确定按钮操作
    submitForm() {
      if (this.form.tzlTzlb == null || this.form.tzlTzlb == "") {
        this.msgError("调整类别不能为空");
        return;
      }
      if (this.form.tzlTzsl == null || this.form.tzlTzsl == "") {
        this.msgError("调整数量不能为空");
        return;
      }
      // if (this.form.tzlTzyy == null || this.form.tzlTzyy == '') {
      //   this.msgError('调整原因不能为空')
      //   return
      // }
      const tzsl = this.form.moeScsl - this.form.moeLpsl;
      if (this.form.tzlTzsl > tzsl) {
        alert("你最多只能调整数量:" + tzsl);
        return;
      }
      const data = {
        tzlTzlb: this.form.tzlTzlb,
        tzlTzsl: this.form.tzlTzsl,
        tzlTzyy: this.form.tzlTzyy,
        tzlMoeid: this.form.moeId,
      };
      adjust(data)
        .then((res) => {
          this.getList();
          this.open = false;
          this.reset();
          this.msgSuccess("成功");
        })
        .catch(() => {
          this.msgError("调整失败");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有工单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          //return exportMoeDet(queryParams)
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    rowClass({ row }) {
      switch (row.moeZtbz) {
        case "1":
          return "jinxing";
        case "2":
          return "dengdai";
        case "3":
          return "zanting";
        case "4":
          return "wancheng";
      }
      return "";
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计:";
          return;
        }
        if (
          ![
            "moeScsl",
            "moeLpsl",
            "moeRksl",
            "moeTzsl",
            "moeTjbl",
            "moeWxbl",
            "moeYxbl",
          ].includes(column.property) ||
          !column.property
        ) {
          sums[index] = " ";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = "N/A";
        }
      });

      return sums;
    },
  },
};
</script>

<style lang="scss" scoped></style>
